package com.ddyx.common.framework.filter;

import com.ddyx.common.utils.io.StringUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 包装httpRequest,并记录访问日志
 * author: agula
 * since: 2019-07-31
 */
@Slf4j
public class LogFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest hsr = (HttpServletRequest) request;
			JsonRequestWrapper requestWrapper = new JsonRequestWrapper(hsr);
			long begin = System.currentTimeMillis();
			try {
				chain.doFilter(requestWrapper, response);
			} catch(Exception ex) {
				log.error(ex.getMessage(), ex);
			}
			long end = System.currentTimeMillis() - begin;
			try {
				String method = hsr.getMethod();
				if (!"HEAD".equalsIgnoreCase(method)) {
					String jsonString = requestWrapper.getJsonString();
					String token = hsr.getHeader("token");
					String ip = "";
					ip = hsr.getHeader("X-Forwarded-For");
					if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
						ip = hsr.getRemoteAddr();
					}
					// 只是为了直观的看一下运行时间长短
					long n = end / 5;
					StringBuffer tmp = new StringBuffer();
					for (long i = 0 ; i < n ; i++) {
						tmp.append("=");
					}
					log.info("method={},address={},url={}?{},body={},token={},time={}{}", method, ip, hsr.getRequestURI(), hsr.getQueryString(), jsonString, token, end, tmp.toString());
				}
			} catch(Exception ex) {
				log.error(ex.getMessage(), ex);
			}
			return;
		}

		chain.doFilter(request, response);

	}

	@Override
	public void destroy() {
		log.info("logFilter destroy...");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		log.info("logFilter init...");
	}
}
